//
//  LXJNavigationController.swift
//  XJWeiBo
//
//  Created by 李旭杰 on 2017/3/26.
//  Copyright © 2017年 李旭杰. All rights reserved.
//

import UIKit

class LXJNavigationController: UINavigationController, UIGestureRecognizerDelegate {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        /// 设置边缘手势代理对象
        self.interactivePopGestureRecognizer?.delegate = self
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: 重写导航控制器的 push 方法
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        /// 表示已经弹出二级控制器
        if viewControllers.count >= 1 {
            /// 表示这是二级控制器
            if viewControllers.count == 1 {
                /// 获取上级控制器的标题
                let title = self.viewControllers.first?.title
                /// 设置本控制器的左边摁扭
                viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(title: title!, imageName: "navigationbar_back_withtext", target:self, action: #selector(backAction))
                
                viewController.navigationItem.title = "\(viewControllers.count + 1)级控制器"
            }
                /// 表示这是二级以上的控制器
            else{
                viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", imageName: "navigationbar_back_withtext", target:self, action: #selector(backAction))
                
                viewController.navigationItem.title = "\(viewControllers.count + 1)级控制器"
            }
            /// 在跳转下一个控制器的时候隐藏 tabBar
            viewController.hidesBottomBarWhenPushed = true
        }
        super.pushViewController(viewController, animated: animated)
    }
    
    // MARK: UIBarButtonItem的点击事件
    @objc private func backAction() -> Void {
        self.popViewController(animated: true)
    }
    
    // MARK: 实现手势识别的代理方法[解决边缘手势]
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        /// 根视图控制器不需要边缘手势
        if viewControllers.count == 1 {
            return false
        }
        return true
    }   
}
